package com.jspgou.cms.action.store;

import static com.jspgou.cms.Constants.RESOURCE_SYS;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.manager.ResourceMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.common.file.FileWrap;
import com.jspgou.common.web.RequestUtils;
import com.jspgou.common.web.ResponseUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;

@Controller
public class ResourceFroAct {
	private static final Logger log = LoggerFactory.getLogger(ResourceFroAct.class);
	
	/**
	 * 店铺资源页
	 */
	public static final String STORE_RESOURCE_MAIN= "tpl.storeResourceMain";
	/**
	 * 店铺资源树页
	 */
	public static final String STORE_RESOURCE_TREE= "tpl.storeResourceTree";
	/**
	 * 店铺资源左侧页
	 */
	public static final String STORE_RESOURCE_LEFT= "tpl.storeResourceLeft";
	/**
	 * 店铺资源列表页
	 */
	public static final String STORE_RESOURCE_LIST= "tpl.storeResourceList";
	/**
	 * 店铺资源重命名页
	 */
	public static final String STORE_RESOURCE_RENAME= "tpl.storeResourceRename";
	/**
	 * 店铺资源添加页
	 */
	public static final String STORE_RESOURCE_ADD= "tpl.storeResourceAdd";
	/**
	 * 店铺资源修改页
	 */
	public static final String STORE_RESOURCE_EDIT= "tpl.storeResourceEdit";
	
	@RequestMapping(value = "/resource/main.jspx")
	public String main(String cl,HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		model.addAttribute("cl", cl);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(RESOURCE_SYS, MessageResolver.getMessage(request,STORE_RESOURCE_MAIN), request);
	}
	
	@RequestMapping(value = "/resource/left.jspx")
	public String left(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(RESOURCE_SYS, MessageResolver.getMessage(request,STORE_RESOURCE_LEFT), request);
	}
	
	@RequestMapping(value = "/resource/tree.jspx")
	public String tree(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		String root = RequestUtils.getQueryParam(request, "root");
		ShopMember member=CmsUtils.getMember(request);
		Store store=member.getStore();
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		log.debug("tree path={}", root);
		boolean isRoot;
		String equipment=(String)request.getAttribute("ua");
		// jquery treeview的根请求为root=source
		if (StringUtils.isBlank(root) || "source".equals(root)) {
			if(StringUtils.isNotBlank(equipment)&&equipment.equals("mobile")){
				root = "/r/store/mobile_u/"+store.getStorePath();
			}else{
				//pc端入口
				root = "/r/store/u/"+store.getStorePath();
			}
			isRoot = true;
		} else {
			isRoot = false;
		}
		model.addAttribute("isRoot", isRoot);
		List<? extends FileWrap> resList = resourceMng.listFile(root, true);
		model.addAttribute("resList", resList);
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(RESOURCE_SYS, MessageResolver.getMessage(request,STORE_RESOURCE_TREE), request);
	}
	
	// 直接调用方法需要把root参数保存至model中
	@RequestMapping(value = "/resource/list.jspx")
	public String list(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		Store store=member.getStore();
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		String roott = (String) model.get("roott");
		if (roott == null) {
			roott = RequestUtils.getQueryParam(request, "roott");
		}
		log.debug("list Resource roott: {}", roott);
		String equipment=(String)request.getAttribute("ua");
		if (StringUtils.isBlank(roott)) {
			//移动端入口
			if(StringUtils.isNotBlank(equipment)&&equipment.equals("mobile")){
				roott = "/r/store/mobile_u/"+store.getStorePath();
			}else{
				//pc端入口
				roott = "/r/store/u/"+store.getStorePath();
			}
		}
//		String rel = roott.substring("/r/store/red".length());
//		if (rel.length() == 0) {
//			rel = "/";
//		}
		model.addAttribute("roott", roott);
//		model.addAttribute("rel", rel);
		model.addAttribute("list", resourceMng.listFile(roott, false));
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(RESOURCE_SYS, MessageResolver.getMessage(request,STORE_RESOURCE_LIST), request);
	}
	
	@RequestMapping(value = "/resource/rename.jspx",method = RequestMethod.GET)
	public String renameInput(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		Store store=member.getStore();
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		String roott = RequestUtils.getQueryParam(request, "roott");
		String name = RequestUtils.getQueryParam(request, "name");
		String equipment=(String)request.getAttribute("ua");
		String path=null;
		//移动端入口
		if(StringUtils.isNotBlank(equipment)&&equipment.equals("mobile")){
			path = "/r/store/mobile_u/"+store.getStorePath();
		}else{
			path = "/r/store/u/"+store.getStorePath();
		}
		String origName = name.substring(path.length());
		model.addAttribute("origName", origName);
		model.addAttribute("roott", roott);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(RESOURCE_SYS, MessageResolver.getMessage(request,STORE_RESOURCE_RENAME), request);
	}

	@RequestMapping(value = "/resource/o_rename.jspx", method = RequestMethod.POST)
	public String renameSubmit(String roott, String origName, String distName,
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		Store store=member.getStore();
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		String equipment=(String)request.getAttribute("ua");
		String path=null;
		//移动端入口
		if(StringUtils.isNotBlank(equipment)&&equipment.equals("mobile")){
			path = "/r/store/mobile_u/"+store.getStorePath();
		}else{
			path = "/r/store/u/"+store.getStorePath();
		}
		String orig = path + origName;
		String dist = path + distName;
		resourceMng.rename(orig, dist);
		log.info("name Resource from {} to {}", orig, dist);
		model.addAttribute("roott", roott);
		ShopFrontHelper.setCommonData(request, model, web);
		return list(request, model);
	}
	
	@RequestMapping(value = "/resource/add.jspx")
	public String add(HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		String roott = RequestUtils.getQueryParam(request, "roott");
		model.addAttribute("roott", roott);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(RESOURCE_SYS, MessageResolver.getMessage(request,STORE_RESOURCE_ADD), request);
	}
	
	@RequestMapping("/resource/save.jspx")
	public String save(String roott, String filename, String source,
			HttpServletRequest request, ModelMap model) throws IOException {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		resourceMng.createFile(roott, filename, source);
		model.addAttribute("roott", roott);
		log.info("save Resource name={}", filename);
		return list(request, model);
	}
	
	@RequestMapping("/resource/edit.jspx")
	public String edit(HttpServletRequest request, ModelMap model)
			throws IOException {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		if(!store.getExamine()){
			return ShopFrontHelper.showMessage(request, model, "error.storeNotCheck");
	    }
		String roott = RequestUtils.getQueryParam(request, "roott");
		String name = RequestUtils.getQueryParam(request, "name");
		model.addAttribute("source", resourceMng.readFile(name));
		model.addAttribute("roott", roott);
		model.addAttribute("name", name);
		model.addAttribute("filename", name
				.substring(name.lastIndexOf('/') + 1));
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(RESOURCE_SYS, MessageResolver.getMessage(request,STORE_RESOURCE_EDIT), request);
	}
	
	// AJAX请求，不返回页面
	@RequestMapping("/resource/o_update.jspx")
	public void update(String roott, String name, String source,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws IOException {
		resourceMng.updateFile(name, source);
		log.info("update Resource name={}.", name);
		model.addAttribute("roott", roott);
		ResponseUtils.renderJson(response, "{success:true}");
	}
	
	@RequestMapping(value = "/resource/o_swfupload.jspx", method = RequestMethod.POST)
	public void swfUpload(
			String roott,
			@RequestParam(value = "Filedata", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws IllegalStateException, IOException {
		resourceMng.saveFile(roott, file);
		model.addAttribute("roott", roott);
		log.info("file upload seccess: {}, size:{}.", file
				.getOriginalFilename(), file.getSize());
		ResponseUtils.renderText(response, "");
	}
	
	@RequestMapping("/resource/o_delete_single.jspx")
	public String deleteSingle(HttpServletRequest request, ModelMap model) {
		// TODO 输入验证
		String roott = RequestUtils.getQueryParam(request, "roott");
		String name = RequestUtils.getQueryParam(request, "name");
		int count = resourceMng.delete(new String[] { name });
		log.info("delete Resource {}, count {}", name, count);
		model.addAttribute("roott", roott);
		return list(request, model);
	}
	
	@RequestMapping(value = "/resource/o_create_dir.jspx")
	public String createDir(String roott, String dirName,
			HttpServletRequest request, ModelMap model) {
		// TODO 检查dirName是否存在
		resourceMng.createDir(roott, dirName);
		model.addAttribute("roott", roott);
		return list(request, model);
	}
	
	private ResourceMng resourceMng;

	@Autowired
	public void setResourceMng(ResourceMng resourceMng) {
		this.resourceMng = resourceMng;
	}
}
